package com.example.wechat;

import org.junit.jupiter.api.Test;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;

public class SocketServer {
    /*
    用于转发通信的服务端
     */
    public static void main(String[] args) {
        ServerSocket serverSocket=null;
        HashMap<String,Socket> CLIENTS_MAP = new HashMap<>();//创建一个map，用于保存客户端连接,key为ip+端口号,value为Socket对象
        try {
            //创建服务端
            serverSocket=new ServerSocket(1024);//0表示随机可用端口
            System.out.println("启动服务,监听端口："+serverSocket.getLocalPort());
            System.out.println("等待连接。。。");
            //连接多个客户端
            while (true) {
                Socket clientSocket=serverSocket.accept();//等待客户端连接
                String ip=clientSocket.getInetAddress().getHostAddress();//获取客户端ip
                System.out.println("连接成功，ip来自："+ip+",端口："+clientSocket.getPort());

                String key=ip+clientSocket.getPort();
                CLIENTS_MAP.put(key,clientSocket);

                //使用线程来处理数据
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        while (true) {
                        /*
                        这里为什么与客户端不同，在循环内创建流？
                        1.服务端需要同时处理多个客户端连接
                        2.每个客户端连接都需要独立的输入输出流
                        3.每个客户端连接的流生命周期与该链接的生命周期一致
                        */
                            try {
                                //读取数据
                                InputStream inputStream= null;//获取输入流
                                inputStream = clientSocket.getInputStream();
                                InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"UTF-8");//创建输入流
                                BufferedReader readerData = new BufferedReader(inputStreamReader);//创建缓冲流
                                String data=readerData.readLine();//读取数据
                                System.out.println("收到来自客户端:"+clientSocket.getPort()+"的数据："+data);

                                //发送数据
//                                OutputStream outputStream=clientSocket.getOutputStream();
//                                PrintWriter printWriter = new PrintWriter(outputStream, true);
//                                printWriter.println("服务端已接收数据:"+ data);
                                //转发当前发送的消息
                                CLIENTS_MAP.forEach((key,value)->{
                                    OutputStream outputStream= null;
                                    try {
                                        outputStream = value.getOutputStream();
                                        //直接包装 OutputStream：PrintWriter → OutputStream，使用系统默认的字符编码
                                        //PrintWriter printWriter = new PrintWriter(outputStream, true);
                                        //通过 OutputStreamWriter 包装：PrintWriter → OutputStreamWriter → OutputStream，使用指定的字符编码
                                        PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(outputStream,"UTF-8"), true);
                                        printWriter.println(clientSocket.getPort()+":"+ data);//群发---转发
                                    } catch (IOException e) {
                                        throw new RuntimeException(e);
                                    }
                                });

                            } catch (IOException e) {
                                e.printStackTrace();
                                break;
                            }
                        }
                    }
                }).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("服务端异常");
        }finally {
            if(serverSocket!=null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
